package com.example.homeworkservice.controller;

import com.example.homeworkservice.entity.homework;
import com.example.homeworkservice.entity.homework_submit;
import com.example.homeworkservice.service.homeworkService;
import com.example.homeworkservice.service.homeworkSubmitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/homework")
public class homeworkController {
    
    @Autowired
    private homeworkService homeworkService;
    
    @Autowired
    private homeworkSubmitService homeworkSubmitService;
    
    // 创建作业
    @PostMapping("/create")
    public String createHomework(@RequestBody Map<String, Object> requestBody) {
        try {
            homework hw = new homework();
            hw.setCourse_id((int) requestBody.get("courseId"));
            hw.setTitle((String) requestBody.get("title"));
            hw.setContent((String) requestBody.get("content"));
            hw.setDdl_time((String) requestBody.get("ddlTime"));
            hw.setTotal_score((double) requestBody.get("totalScore"));
            hw.setCreated_by((int) requestBody.get("createdBy"));
            
            // 设置创建时间
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            hw.setCreated_at(currentTime);
            
            homeworkService.save(hw);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "创建作业失败: " + e.getMessage();
        }
    }
    
    // 获取课程的作业列表
    @GetMapping("/course/{courseId}")
    public List<homework> getCourseHomeworks(@PathVariable int courseId) {
        return homeworkService.lambdaQuery()
                .eq(homework::getCourse_id, courseId)
                .orderByDesc(homework::getCreated_at)
                .list();
    }
    
    // 获取作业详情
    @GetMapping("/{homeworkId}")
    public homework getHomeworkDetail(@PathVariable int homeworkId) {
        return homeworkService.getById(homeworkId);
    }
    
    // 更新作业
    @PutMapping("/update")
    public String updateHomework(@RequestBody Map<String, Object> requestBody) {
        try {
            int homeworkId = (int) requestBody.get("homeworkId");
            homework hw = homeworkService.getById(homeworkId);
            if (hw == null) {
                return "作业不存在";
            }
            
            hw.setTitle((String) requestBody.get("title"));
            hw.setContent((String) requestBody.get("content"));
            hw.setDdl_time((String) requestBody.get("ddlTime"));
            hw.setTotal_score((double) requestBody.get("totalScore"));
            
            homeworkService.updateById(hw);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新作业失败: " + e.getMessage();
        }
    }
    
    // 删除作业
    @DeleteMapping("/{homeworkId}")
    public String deleteHomework(@PathVariable int homeworkId) {
        try {
            homeworkService.removeById(homeworkId);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除作业失败: " + e.getMessage();
        }
    }
    
    // ==================== 作业提交相关API ====================
    
    // 学生提交作业
    @PostMapping("/submit")
    public String submitHomework(@RequestBody Map<String, Object> requestBody) {
        try {
            homework_submit submit = new homework_submit();
            submit.setHomework_id((int) requestBody.get("homeworkId"));
            submit.setUser_id((int) requestBody.get("userId"));
            submit.setContent_text((String) requestBody.get("contentText"));
            submit.setFile_url((String) requestBody.get("fileUrl"));
            
            // 设置提交时间
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            submit.setSubmitted_at(currentTime);
            
            homeworkSubmitService.save(submit);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "提交作业失败: " + e.getMessage();
        }
    }
    
    // 获取学生的作业提交记录
    @GetMapping("/submissions/student/{userId}")
    public List<Map<String, Object>> getStudentSubmissions(@PathVariable int userId) {
        return homeworkSubmitService.getStudentSubmissions(userId);
    }
    
    // 获取学生应该看到的所有作业（包括已提交和未提交的）
    @GetMapping("/student/{userId}")
    public List<Map<String, Object>> getStudentHomeworks(@PathVariable int userId) {
        return homeworkSubmitService.getStudentHomeworks(userId);
    }
    
    // 获取作业的所有提交记录
    @GetMapping("/submissions/homework/{homeworkId}")
    public List<Map<String, Object>> getHomeworkSubmissions(@PathVariable int homeworkId) {
        return homeworkSubmitService.getHomeworkSubmissions(homeworkId);
    }
    
    // 获取学生特定作业的提交记录
    @GetMapping("/submissions/student/{userId}/homework/{homeworkId}")
    public Object getStudentHomeworkSubmission(@PathVariable int userId, @PathVariable int homeworkId) {
        // 先获取作业信息
        homework hw = homeworkService.getById(homeworkId);
        if (hw == null) {
            return "作业不存在";
        }
        
        // 获取提交记录
        homework_submit submission = homeworkSubmitService.getStudentHomeworkSubmission(userId, homeworkId);
        
        // 构建返回对象
        Map<String, Object> result = new HashMap<>();
        result.put("id", hw.getId());
        result.put("title", hw.getTitle());
        result.put("content", hw.getContent());
        result.put("ddl_time", hw.getDdl_time());
        result.put("total_score", hw.getTotal_score());
        result.put("created_at", hw.getCreated_at());
        
        if (submission != null) {
            result.put("content_text", submission.getContent_text());
            result.put("submitted_at", submission.getSubmitted_at());
            result.put("score", submission.getScore());
            result.put("feedback", submission.getFeedback());
        }
        
        return result;
    }
    
    // 教师批改作业
    @PutMapping("/grade")
    public String gradeHomework(@RequestBody Map<String, Object> requestBody) {
        try {
            int submissionId = (int) requestBody.get("submissionId");
            System.out.println(submissionId);
            String scoreStr = (String) requestBody.get("score");
            String feedback = (String) requestBody.get("feedback");
            int gradedBy = (int) requestBody.get("gradedBy");
            
            // 转换score为BigDecimal
            java.math.BigDecimal score = null;
            if (scoreStr != null && !scoreStr.trim().isEmpty()) {
                try {
                    score = new java.math.BigDecimal(scoreStr);
                } catch (NumberFormatException e) {
                    return "分数格式错误";
                }
            }

            homework_submit submission = homeworkSubmitService.getById(submissionId);
            if (submission == null) {
                return "提交记录不存在";
            }
            

//            System.out.println("=== 作业提交记录调试 ===");
//            System.out.println("ID: " + submission.getId());
//            System.out.println("Homework ID: " + submission.getHomework_id());
//            System.out.println("User ID: " + submission.getUser_id());
//            System.out.println("Content Text: " + submission.getContent_text());
//            System.out.println("File URL: " + submission.getFile_url());
//            System.out.println("Submitted At: " + submission.getSubmitted_at());
//            System.out.println("Score: " + submission.getScore());
//            System.out.println("Graded By: " + submission.getGraded_by());
//            System.out.println("Graded At: " + submission.getGraded_at());
//            System.out.println("Feedback: " + submission.getFeedback());
//            System.out.println("========================");

            homework homework = homeworkService.getById(submission.getHomework_id());
            if (homework == null) {
                return "关联的作业不存在，无法批改";
            }

            submission.setScore(score);
            submission.setFeedback(feedback);
            submission.setGraded_by(gradedBy);

            // 设置批改时间
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            submission.setGraded_at(currentTime);
            
            homeworkSubmitService.updateById(submission);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "批改作业失败: " + e.getMessage();
        }
    }
}
